﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace iNet.Media.Imaging.Filters
{
	/// <summary>
	/// 矩形平均化濾鏡工作。
	/// </summary>
	public class MeanFilterTask : SeparableKernelCorrelationFilterTask
	{
		#region 欄位
		int _Radius;
        #endregion
		#region 建構子
		/// <summary>
		/// 初始化新的 MeanFilterTask 執行個體。
		/// </summary>
		public MeanFilterTask()
		{
			this.Radius = 2;
		}
		/// <summary>
		/// 初始化新的 MeanFilterTask 執行個體。
		/// </summary>
		/// <param name="sourceImage">來源點陣圖。</param>
		public MeanFilterTask(IBitmapImage sourceImage)
			: this(sourceImage, 2)
		{ }
		/// <summary>
		/// 初始化新的 MeanFilterTask 執行個體。
		/// </summary>
		/// <param name="sourceImage">來源點陣圖。</param>
		/// <param name="radius">平均化半徑，單位為像素。</param>
		public MeanFilterTask(IBitmapImage sourceImage, int radius)
			: base(sourceImage)
		{
			this.Radius = radius;
		}
        #endregion
		#region Radius
		/// <summary>
		/// 取得或設定平均化半徑，單位為像素，初始值為 2。
		/// </summary>
		public int Radius
		{
			get
			{
				return _Radius;
			}
			set
			{
				if (value < 0)
					throw new ArgumentOutOfRangeException();
				lock (this.SyncRoot)
				{
					if (this.State == Tasks.TaskState.Initializing)
					{
						//更新欄位
						_Radius = value;

						//計算 Kernel
						int kernelSize = ((value * 2) + 1);
						double weight = (1.0 / kernelSize);
						double total = 0;
						double[] kernel = new double[kernelSize];
						for (int i = kernelSize - 1; i >= 0; --i)
							kernel[i] = weight;
						kernel[value] = (1 - (weight * (kernelSize - 1)));

						//更新 Kernel
						SeparableCorrelationKernels kernels = new SeparableCorrelationKernels();
						kernels.SetArgbKernels(kernel);
						kernels.HorizontalLuminanceKernel = kernel;
						kernels.VerticalLuminanceKernel = kernel;
						this.Kernels = kernels;
					}
					else
						throw new InvalidOperationException();
				}
			}
		}
        #endregion
	}
}
